// pages/collection/index.js
const api = require('../../config/api.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loadding: false,
    userId: null,
    pageNum: 1,
    total: 0,
    list: []
  },

  initData(){
    this.setData({
      pageNum: 1,
      total: 0,
      list: []
    })
  },
  getList() {
    if (this.data.total > 0 && this.data.list.length >= this.data.total) {
      this.setData({
        pageNum: this.data.pageNum - 1
      })
      return
    }
    this.setData({
      loadding: true
    })
    wx.request({
      url: api.collectListUrl,
      data: {
        userId: this.data.userId,
        pageNum: this.data.pageNum,
        pageSize: 10
      },
      method: 'GET',
      success: (res) => {
        this.setData({
          loadding: false
        })
        if (res.data.code === 200) {
          let objs = res.data.collect.records || []
          this.data.total = res.data.collect.total || 0
          let list = this.data.list || []
          list = list.concat(objs)
          this.setData({
            list: list
          })
        }
      },
      fail: (err => {
        console.log(err)
        this.setData({
          loadding: false
        })
      }),
    });
  },

  collectionClick(options) {
    const {
      position,
      name
    } = options.detail;
    switch (position) {
      case 'right':
        const data = options.currentTarget.dataset
        wx.request({
          url: api.collectSaveUrl, //仅为示例，并非真实接口地址。
          data: {
            collectType: 0,
            createTime: '',
            enterpriseId: data.enterpriseid,
            id: data.id,
            userId: this.data.userId
          },
          method: 'POST',
          success: (res) => {
            if (res.data.code === 200) {
              wx.showToast({
                title: '操作成功'
              });
              this.initData()
              this.getList()
            }
          }
        });
        break;
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let userId = options.userId
    if (!userId) {
      userId = wx.getStorageSync('wxUser') ? wx.getStorageSync('wxUser').id : ''
    }
    this.data.userId = userId
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.initData()
    this.getList()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.setData({
      pageNum: this.data.pageNum + 1
    })
    this.getList();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})